/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ItemFrame.java
 *
 * Created on 16-06-2011, 18:40:55
 */
package ui.gui;

import controller.ItemController;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.regex.Pattern;
import javax.swing.JOptionPane;
import javax.swing.ListSelectionModel;
import javax.swing.RowFilter;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.TableRowSorter;
import model.DuplicateItemIdentifierException;
import model.Item;
import ui.gui.table.model.ItemTableModel;
import ui.gui.table.renderer.DecimalCellRenderer;

/**
 *
 * @author Martin Mohr Pedersen
 */
public class ItemFrame extends javax.swing.JFrame {

    private ItemController controller;
    private ItemTableModel tableModel;
    private Item selectedItem;

    /** Creates new form ItemFrame */
    public ItemFrame() {

        controller = new ItemController();
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        initComponents();
        initTable();
    }

    private void initTable() {
        tableModel = new ItemTableModel();
        tblItems.setModel(tableModel);

        tblItems.setDefaultRenderer(java.lang.Double.class, new DecimalCellRenderer(2));

        ListSelectionModel selectionModel = tblItems.getSelectionModel();
        selectionModel.addListSelectionListener(new ListSelectionListener() {

            @Override
            public void valueChanged(ListSelectionEvent e) {
                if (e.getValueIsAdjusting()) {
                    return;
                }

                int index = tblItems.convertRowIndexToModel(tblItems.getSelectedRow());
                selectedItem = tableModel.getItemAtIndex(index);
                updateItemFields();
            }
        });
    }

    private void updateItemFields() {
        Item item = selectedItem;
        btnItemInfoEditItem.setEnabled(true);
        txtItemInfoItemNo.setText(item.getItemNo());
        txtItemInfoItemName.setText(item.getName());
        txtItemInfoItemPrice.setText(String.format("%.2f", item.getPrice()));
        txtItemDescription.setText(item.getDescription());
        txtItemDiscount.setText(String.format("%.0f", item.getDiscount()));
    }

    private void filterItems(String query) {
        TableRowSorter<ItemTableModel> sorter = new TableRowSorter<ItemTableModel>(tableModel);
        tblItems.setRowSorter(sorter);

        String filterText = query;

        if (filterText.length() == 0) {
            sorter.setRowFilter(null);
        } else {
            try {
                sorter.setRowFilter(RowFilter.regexFilter("(?i)" + Pattern.quote(filterText)));
            } catch (Exception e) {
                // TODO: Log failures
            }
        }
    }

    /** This method is called from within the constructor to
     * initialise the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        pnlSearch = new javax.swing.JPanel();
        txtSearchItem = new javax.swing.JTextField();
        btnSearchItemClear = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblItems = new javax.swing.JTable();
        pnlEditor = new javax.swing.JPanel();
        lblItemInfoItemNoTxt = new javax.swing.JLabel();
        lblItemInfoItemNameTxt = new javax.swing.JLabel();
        lblItemInfoItemDescriptionTxt = new javax.swing.JLabel();
        lblItemInfoItemPriceTxt = new javax.swing.JLabel();
        txtItemInfoItemNo = new javax.swing.JTextField();
        txtItemInfoItemName = new javax.swing.JTextField();
        txtItemInfoItemPrice = new javax.swing.JTextField();
        btnItemInfoCreateItem = new javax.swing.JButton();
        btnItemInfoEditItem = new javax.swing.JButton();
        txtItemDescription = new javax.swing.JTextField();
        lblItemDiscount = new javax.swing.JLabel();
        txtItemDiscount = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setMinimumSize(new java.awt.Dimension(900, 420));

        pnlSearch.setBorder(javax.swing.BorderFactory.createTitledBorder("Søg efter varer"));

        txtSearchItem.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtSearchItemKeyReleased(evt);
            }
        });

        btnSearchItemClear.setText("Ryd");
        btnSearchItemClear.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSearchItemClearActionPerformed(evt);
            }
        });

        tblItems.setAutoCreateRowSorter(true);
        tblItems.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        tblItems.getTableHeader().setReorderingAllowed(false);
        jScrollPane1.setViewportView(tblItems);

        javax.swing.GroupLayout pnlSearchLayout = new javax.swing.GroupLayout(pnlSearch);
        pnlSearch.setLayout(pnlSearchLayout);
        pnlSearchLayout.setHorizontalGroup(
            pnlSearchLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlSearchLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(pnlSearchLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 511, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnlSearchLayout.createSequentialGroup()
                        .addComponent(txtSearchItem, javax.swing.GroupLayout.DEFAULT_SIZE, 454, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnSearchItemClear)))
                .addContainerGap())
        );
        pnlSearchLayout.setVerticalGroup(
            pnlSearchLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlSearchLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(pnlSearchLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtSearchItem, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnSearchItemClear))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 315, Short.MAX_VALUE)
                .addContainerGap())
        );

        pnlEditor.setBorder(javax.swing.BorderFactory.createTitledBorder("Vareinformationer"));

        lblItemInfoItemNoTxt.setText("Varenr:");

        lblItemInfoItemNameTxt.setText("Vare navn:");

        lblItemInfoItemDescriptionTxt.setText("Vare beskrivelse:");

        lblItemInfoItemPriceTxt.setText("Grund-pris");

        txtItemInfoItemNo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtItemInfoItemNoActionPerformed(evt);
            }
        });
        txtItemInfoItemNo.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                txtItemInfoItemNoFocusGained(evt);
            }
        });

        txtItemInfoItemName.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                txtItemInfoItemNameFocusGained(evt);
            }
        });

        txtItemInfoItemPrice.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                txtItemInfoItemPriceFocusGained(evt);
            }
        });

        btnItemInfoCreateItem.setText("Opret varer");
        btnItemInfoCreateItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnItemInfoCreateItemActionPerformed(evt);
            }
        });

        btnItemInfoEditItem.setText("Gem ændringer");
        btnItemInfoEditItem.setEnabled(false);
        btnItemInfoEditItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnItemInfoEditItemActionPerformed(evt);
            }
        });

        txtItemDescription.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                txtItemDescriptionFocusGained(evt);
            }
        });

        lblItemDiscount.setText("Rabat (%):");

        javax.swing.GroupLayout pnlEditorLayout = new javax.swing.GroupLayout(pnlEditor);
        pnlEditor.setLayout(pnlEditorLayout);
        pnlEditorLayout.setHorizontalGroup(
            pnlEditorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlEditorLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(pnlEditorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(lblItemInfoItemNameTxt)
                    .addComponent(lblItemInfoItemNoTxt)
                    .addComponent(lblItemInfoItemDescriptionTxt)
                    .addComponent(lblItemInfoItemPriceTxt))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(pnlEditorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(pnlEditorLayout.createSequentialGroup()
                        .addComponent(btnItemInfoEditItem)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnItemInfoCreateItem))
                    .addComponent(txtItemInfoItemNo, javax.swing.GroupLayout.DEFAULT_SIZE, 202, Short.MAX_VALUE)
                    .addComponent(txtItemInfoItemName, javax.swing.GroupLayout.DEFAULT_SIZE, 202, Short.MAX_VALUE)
                    .addComponent(txtItemDescription, javax.swing.GroupLayout.DEFAULT_SIZE, 202, Short.MAX_VALUE)
                    .addGroup(pnlEditorLayout.createSequentialGroup()
                        .addComponent(txtItemInfoItemPrice, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(lblItemDiscount)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtItemDiscount, javax.swing.GroupLayout.DEFAULT_SIZE, 68, Short.MAX_VALUE)))
                .addContainerGap())
        );
        pnlEditorLayout.setVerticalGroup(
            pnlEditorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlEditorLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(pnlEditorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblItemInfoItemNoTxt)
                    .addComponent(txtItemInfoItemNo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(pnlEditorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblItemInfoItemNameTxt)
                    .addComponent(txtItemInfoItemName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(pnlEditorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtItemDescription, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblItemInfoItemDescriptionTxt))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(pnlEditorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtItemInfoItemPrice, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblItemInfoItemPriceTxt)
                    .addComponent(txtItemDiscount, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblItemDiscount))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(pnlEditorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnItemInfoEditItem)
                    .addComponent(btnItemInfoCreateItem))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(pnlSearch, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(pnlEditor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(pnlEditor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(pnlSearch, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void txtItemInfoItemNoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtItemInfoItemNoActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtItemInfoItemNoActionPerformed

    private void btnItemInfoEditItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnItemInfoEditItemActionPerformed
        String name = txtItemInfoItemName.getText();
        String description = txtItemDescription.getText();
        String itemNo = txtItemInfoItemNo.getText();
        String price = txtItemInfoItemPrice.getText();
        String discount = txtItemDiscount.getText();

        if (name.length() == 0 || itemNo.length() == 0 || price.length() == 0) {
            JOptionPane.showMessageDialog(this, "Et eller flere påkrævede felter er tomme",
                    null, JOptionPane.WARNING_MESSAGE);
        } else {



            double priceDoub = 0;
            try {
                priceDoub = NumberFormat.getInstance().parse(price).doubleValue();
            } catch (ParseException pe) {
                JOptionPane.showMessageDialog(this, "Pris skal være et tal",
                        null, JOptionPane.WARNING_MESSAGE);
                return;
            }

            double discountDoub = 0;


            try {
                discountDoub = NumberFormat.getInstance().parse(discount).doubleValue();
            } catch (ParseException pe) {
                JOptionPane.showMessageDialog(this, "Discount skal være et tal",
                        null, JOptionPane.WARNING_MESSAGE);
                return;
            }

            try {
                controller.addItem(name, description, itemNo, priceDoub, discountDoub);
            } catch (DuplicateItemIdentifierException ex) {
                JOptionPane.showMessageDialog(this, "Denne vare findes allerede",
                        null, JOptionPane.WARNING_MESSAGE);
                return;
            }

            controller.editItem(selectedItem, itemNo, name, description,
                    priceDoub, discountDoub);

            int firstRow = tblItems.getSelectedRow();
            int lastRow = firstRow;
            tableModel.fireTableRowsUpdated(firstRow, lastRow);

        }
    }//GEN-LAST:event_btnItemInfoEditItemActionPerformed

    private void btnItemInfoCreateItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnItemInfoCreateItemActionPerformed
        String name = txtItemInfoItemName.getText();
        String description = txtItemDescription.getText();
        String itemNo = txtItemInfoItemNo.getText();
        String price = txtItemInfoItemPrice.getText();
        String discount = txtItemDiscount.getText();

        if (name.length() == 0 || itemNo.length() == 0 || price.length() == 0) {
            JOptionPane.showMessageDialog(this, "Et eller flere påkrævede felter er tomme",
                    null, JOptionPane.WARNING_MESSAGE);
        } else {

            double priceDoub = 0;

            try {
                priceDoub = NumberFormat.getInstance().parse(price).doubleValue();
            } catch (ParseException ex) {
                JOptionPane.showMessageDialog(this, "Pris skal være et tal",
                        null, JOptionPane.WARNING_MESSAGE);
                return;
            }

            double discountDoub = 0;

            try {
                discountDoub = NumberFormat.getInstance().parse(discount).doubleValue();
            } catch (ParseException ex) {
                JOptionPane.showMessageDialog(this, "Discount skal være et tal",
                        null, JOptionPane.WARNING_MESSAGE);
                return;
            }

            try {
                controller.addItem(name, description, itemNo, priceDoub, discountDoub);
            } catch (DuplicateItemIdentifierException ex) {
                JOptionPane.showMessageDialog(this, "Denne vare findes allerede",
                        null, JOptionPane.WARNING_MESSAGE);
                return;
            }

            int lastRow = controller.getItemCount() - 1;
            tableModel.fireTableRowsInserted(lastRow, lastRow);

            selectedItem = tableModel.getItemAtIndex(lastRow);
            updateItemFields();



        }

    }//GEN-LAST:event_btnItemInfoCreateItemActionPerformed

    private void btnSearchItemClearActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSearchItemClearActionPerformed
        txtSearchItem.setText("");
        filterItems("");
    }//GEN-LAST:event_btnSearchItemClearActionPerformed

    private void txtSearchItemKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtSearchItemKeyReleased
        filterItems(txtSearchItem.getText());
    }//GEN-LAST:event_txtSearchItemKeyReleased

    private void txtItemInfoItemNoFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtItemInfoItemNoFocusGained
        txtItemInfoItemNo.selectAll();
    }//GEN-LAST:event_txtItemInfoItemNoFocusGained

    private void txtItemInfoItemNameFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtItemInfoItemNameFocusGained
        txtItemInfoItemName.selectAll();
    }//GEN-LAST:event_txtItemInfoItemNameFocusGained

    private void txtItemDescriptionFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtItemDescriptionFocusGained
        txtItemDescription.selectAll();
    }//GEN-LAST:event_txtItemDescriptionFocusGained

    private void txtItemInfoItemPriceFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtItemInfoItemPriceFocusGained
        txtItemInfoItemPrice.selectAll();
    }//GEN-LAST:event_txtItemInfoItemPriceFocusGained
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnItemInfoCreateItem;
    private javax.swing.JButton btnItemInfoEditItem;
    private javax.swing.JButton btnSearchItemClear;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lblItemDiscount;
    private javax.swing.JLabel lblItemInfoItemDescriptionTxt;
    private javax.swing.JLabel lblItemInfoItemNameTxt;
    private javax.swing.JLabel lblItemInfoItemNoTxt;
    private javax.swing.JLabel lblItemInfoItemPriceTxt;
    private javax.swing.JPanel pnlEditor;
    private javax.swing.JPanel pnlSearch;
    private javax.swing.JTable tblItems;
    private javax.swing.JTextField txtItemDescription;
    private javax.swing.JTextField txtItemDiscount;
    private javax.swing.JTextField txtItemInfoItemName;
    private javax.swing.JTextField txtItemInfoItemNo;
    private javax.swing.JTextField txtItemInfoItemPrice;
    private javax.swing.JTextField txtSearchItem;
    // End of variables declaration//GEN-END:variables
}
